package mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import objects.Person;

public class PersonQueries {

	private static final String DATABASE_URL = "jdbc:mysql://localhost/MovieBase";
	private static final String USERNAME = "moviebase";
	private static final String PASSWORD = "moviebase";

	private Connection connection = null;
	private PreparedStatement selectAllPeople = null;
	private PreparedStatement insertNewPerson = null;

	public PersonQueries() {
		try {
			try {
				Class.forName("com.mysql.jdbc.Driver");
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			connection = DriverManager.getConnection(DATABASE_URL, USERNAME,
					PASSWORD);

			selectAllPeople = connection
					.prepareStatement("SELECT * FROM Person");

			insertNewPerson = connection
					.prepareStatement("INSERT INTO Person (pid, forname, lastname, lid) VALUES "
							+ "(?,?,?,?)");
		} catch (SQLException e) {
			System.out.println(e);
		}
	}

	public List<Person> getAllPeople() {
		List<Person> results = null;
		ResultSet resultSet = null;

		try {
			resultSet = selectAllPeople.executeQuery();
			results = new ArrayList<Person>();

			while (resultSet.next()) {
				results.add(new Person(resultSet.getInt("pid"),resultSet.getString("forname"),
						resultSet.getString("lastname"), resultSet
								.getInt("lid")));
			}
		} catch (SQLException e) {
			System.out.println(e);
		} finally {
			try {
				resultSet.close();
			} catch (SQLException e) {

			}
		}
		return results;
	}
	
	public int addPerson(int pid, String fname, String lname, int loc) {
		int result = 0;
		
		try {
			insertNewPerson.setInt(1, pid);
			insertNewPerson.setString(2, fname);
			insertNewPerson.setString(3, lname);
			insertNewPerson.setInt(4, loc);
			
			result = insertNewPerson.executeUpdate();
		}
		catch (SQLException e) {
			System.out.println(e);
			close();
		}
		
		return result;
	}
	
	public void close() {
		try {
			connection.close();
		}
		catch (SQLException e) {
			System.out.println(e);
		}
	}
}
